<template>
  <el-card shadow="hover" class="cardClass" :style="cssVars"  >
    <template #header>
      <div class="option-header">
        <div class="option-header-content"><span>香草期权</span></div>
        <div v-if="props.calcSuccess=='true'" class="option-header-content"><span style="color: #22bb98 ">计算成功</span></div>
<!--        <div v-if="props.calcSuccess=='false'" class="option-header-content"><span style="color: #e53c3c">计算失败</span></div>-->
        <div v-if="props.calcSuccess=='false'" class="option-header-content">
          <el-tooltip  effect="light"  >
            <template #content> <div style="width: 280px;">
              <span style="color: #e53c3c;">{{props.errorMsg}}</span>
            </div> </template>
            <span style="color: #e53c3c">计算失败</span>
          </el-tooltip>
        </div>
        <div>
          <el-button style="background: transparent;" :disabled="cpoyWait" v-if="props.useType=='calc'" class="delete" @click="copy" title="复制">
            <el-icon>
              <copy-document/>
            </el-icon>
          </el-button>
          <el-button style="background: transparent;" class="delete" @click="cancel" title="关闭">
            <el-icon>
              <circle-close/>
            </el-icon>
          </el-button>
        </div>
      </div>
    </template>

    <el-form ref="formRef" :disabled="form.data.readOnly" :model="form.data" label-width="auto" size="small"
             :rules="rules">
      <div class="optionst01">
        <el-form-item label="行权方式">
          <el-radio-group v-model="form.data.exerciseType" size="small" :fill="getColor()">
            <el-radio label="European">欧式行权</el-radio>
            <el-radio label="American">美式行权</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="交易方向" prop="payDirection">
          <el-radio-group v-model="form.data.payDirection" size="small" :fill="getColor()">
            <el-radio-button label="1">买入</el-radio-button>
            <el-radio-button label="-1">卖出</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="标的" label-width="auto" prop="instrumentId">
          <Underlyer v-model="form.data.instrumentId" @change="onBlurInstrumentId" :underlyerId="form.data.instrumentId" :filterDate="true"  ref="underlyerIdRef"/>
        </el-form-item>
        <!--合约乘数-->
        <!--      todo-->
        <!--涨跌类型-->
        <el-form-item label="涨跌类型" label-width="auto" prop="optionType">
          <el-radio-group v-model="form.data.optionType" size="small">
            <el-radio label="Call">看涨</el-radio>
            <el-radio label="Put">看跌</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="起始日" label-width="auto" prop="effectiveDate">
          <el-date-picker value-format="YYYY-MM-DD" v-model="form.data.effectiveDate" @blur="onBlurEffectiveDate" type="date" placeholder="">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="期限" label-width="auto" prop="term">
          <Numberinput maxlength="4" v-model="form.data.term" min="0" append="D"/>
        </el-form-item>

        <el-form-item label="到期日" label-width="auto" prop="terminationDate">
          <el-date-picker value-format="YYYY-MM-DD" v-model="form.data.terminationDate" type="date" placeholder=""/>
        </el-form-item>

        <el-form-item label="到期支付偏移" label-width="auto" prop="paymentDaysOffset">
          <Numberinput maxlength="4" v-model="form.data.paymentDaysOffset"  append="D"/>

        </el-form-item>

        <el-form-item label="到期支付日" label-width="auto" prop="terminationDate">
          <el-date-picker value-format="YYYY-MM-DD" v-model="form.data.terminationPaymentDate"
                          type="date"
                          placeholder=""/>
        </el-form-item>

        <el-form-item v-if="form.data.exerciseType=='American'" label="行权开始日" label-width="auto"
                      prop="startDate">
          <el-date-picker value-format="YYYY-MM-DD" v-model="form.data.startDate" type="date" placeholder="">
          </el-date-picker>
          <!--          </el-col>-->
        </el-form-item>

        <el-form-item v-if="form.data.exerciseType=='American'" label="行权结束日" label-width="auto" prop="endDate">

          <!--          <el-col :span="8">-->
          <!--            <el-checkbox-group v-model="form.data.isIncludeEndDate" size="small">-->
          <!--              <el-checkbox label="包含" name="type">包含</el-checkbox>-->
          <!--            </el-checkbox-group>-->
          <!--          </el-col>-->
          <!--          <el-col :span="16">-->
          <el-date-picker value-format="YYYY-MM-DD" v-model="form.data.endDate" type="date" placeholder="">
          </el-date-picker>
          <!--          </el-col>-->
        </el-form-item>

        <el-form-item label="名义本金" prop="notional">
          <InputAmount maxlength="20" v-model:value="form.data.notional" append="元" precision="2"></InputAmount>
        </el-form-item>

        <el-form-item label="期初价格" label-width="auto" prop="spotPrice">
          <el-col :span="8">
            <el-checkbox name="status" false-label="0" true-label="1" v-model="form.data.priceOnWait">待定</el-checkbox>
          </el-col>
          <el-col :span="16">
            <InputAmount v-model:value="form.data.spotPrice" maxlength="20" :disabled="form.data.priceOnWait=='1'"
                         append="元" precision="2"/>
          </el-col>
        </el-form-item>

        <el-form-item label="交易数量" prop="optionEntitlement">
          <Numberinput v-model="form.data.optionEntitlement" precision="2" maxlength="20" :disabled="form.data.priceOnWait=='1'"  @change="optionEntitlementChange"/>
        </el-form-item>
        <el-form-item label="参与率" prop="participationRate">
          <Numberinput v-model="form.data.participationRate" maxlength="20" precision="2" append="%"/>
        </el-form-item>
      </div>
      <!---------------------------------------------- 分割线---------------------------------------------------------->
      <div class="optionst02">
        <el-form-item label="行权价比例" prop='strikePercentage'>
          <Numberinput v-model="form.data.strikePercentage" precision="2" maxlength="18" @blur="linkPercentage(form,form.data.strikePercentage,form.data.spotPrice,'data.strike')" 
          @change="() => {proxy.$refs.PricingParamRef?proxy.$refs.PricingParamRef.calcRateByCode():''}" :input-style="Dialog.type=='strikePercentage'?'color: red;':''" append="%"/>
        </el-form-item>
        <el-form-item label="行权价" prop='strike'>
          <Numberinput v-model="form.data.strike" precision="2" maxlength="20" :input-style="Dialog.type=='strikePercentage'?'color: red;':''" @blur="linkPrice(form,form.data.strike,form.data.spotPrice,'data.strikePercentage')" 
          @change="() => {proxy.$refs.PricingParamRef?proxy.$refs.PricingParamRef.calcRateByCode():''}"/>
        </el-form-item>
        <el-form-item label="是否年化">
          <dictCombox v-model="form.data.moneynessOption"
                      dictType="boolType"
                      :style="{width: '100%'}"></dictCombox>
        </el-form-item>

        <el-form-item v-show="form.data.moneynessOption>0" label="计息基准" prop="daycounter">
          <dictCombox v-model="form.data.daycounter" prop='disDayCount'
                      dictType="dayCounter"
                      :style="{width: '100%'}"></dictCombox>
        </el-form-item>

        <el-form-item class="operation">
          <el-button type="primary" @click="calc" v-show="props.useType=='calc'||props.useType=='scene'"
                     :disabled="form.data.priceOnWait=='1'">计算
          </el-button>
          <el-button type="primary" @click="calcInvert" v-show="props.useType=='calc'||props.useType=='scene'"
                     :disabled="form.data.priceOnWait=='1'">反算
          </el-button>
<!--          <el-button type="primary" @click="marketNPV" v-show="props.useType=='calc'"
                     v-if="form.data.exerciseType=='European'&&props.useType!='scene'"
                     :disabled="form.data.priceOnWait=='1'">反算波动率
          </el-button>-->
          <!--          <el-button @click="save2Trade" v-show="props.useType=='calc'">保存</el-button>-->
          <el-button @click="save2CalcLog" v-show="props.useType=='calc'" :disabled="form.data.priceOnWait=='1'">存为草稿</el-button>
        </el-form-item>
      </div>
    </el-form>
    <div class="optionst03">
      <PricingParam ref="PricingParamRef" :formData="form.data"  :valueDate="props.valueDate"  :exerciseType="form.data.exerciseType" :index="props.index"
                    label-width="auto" :filterList="form.data.filterList" :disabled="form.data.readOnly"
                    :productType="productType" size="small"
                    :calcPricingParam="props.calcPricingParam"></PricingParam>
    </div>
    <!--  todo 情景因子  -->
    <!--  todo 结果  -->
    <div v-show="props.useType!='scene'">
      <singleResult ref="resultCompRef" :result="form.result" :index="props.index" :hasExport=true :calcInvert="props.useType=='calc'"></singleResult>
<!--                    :calcMarketNpv="props.useType=='calc'"></singleResult>-->
    </div>
    <div v-if="props.useType!='scene'&&showVolRatesResult">
      <volRatesResult :calcMarketNpvResult="props.calcMarketNpvResult"/>
    </div>
  </el-card>
  <el-dialog
      v-model="calcInvertVisible"
      title="反算结果"
      width="20%"
      destroy-on-close
      center
  >
    <el-form ref="DialogForm" disabled :model="Dialog.data" label-width="auto" size="small">
      <el-form-item v-if="Dialog.showMoneynessOption" :label="Dialog.data.labelPercentage">
        <el-col :span="8">
          <el-checkbox v-model="Dialog.data.moneynessOption" name="status" false-label="0" true-label="1">年化
          </el-checkbox>
        </el-col>
        <el-col :span="16">
          <Numberinput v-model="Dialog.data.valuePercentage" maxlength="18" precision="2" append="%"/>
        </el-col>
      </el-form-item>
      <el-form-item v-if="!Dialog.showMoneynessOption" :label="Dialog.data.labelPercentage">
        <Numberinput v-model="Dialog.data.valuePercentage" maxlength="18" precision="2" append="%"/>
      </el-form-item>
      <el-form-item :label="Dialog.data.labelAmount">
        <Numberinput v-model="Dialog.data.valueAmount" maxlength="18" precision="2" append="元"/>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import {
  getCurrentInstance,
  onMounted,
  onUpdated,
  provide,
  reactive,
  ref,
  toRefs,
  watch,
  toRaw,
  watchEffect,
  onBeforeMount, nextTick
} from 'vue'
import Underlyer from '@/xquant/base/underlyer'
import Numberinput from '@/xquant/base/number'
import InputAmount from '@/xquant/base/InputAmount'
import dictCombox from '@/xquant/base/dictCombox'
import PricingParam from '@/views/calc/otcOtion/pricingparam/index'
import singleResult from '@/views/calc/otcOtion/result/single'
import volRatesResult from '@/views/calc/otcOtion/result/volRatesResult'
import {getTradeDay} from '@/utils/calc'
import {isVoid, isNotVoid} from '@/utils/util'
import {getTerminationPaymentDate,calcContractParamProxy,getOffset} from '@/api/calc/otcOption/calc'
import {debounce} from 'lodash'
import {setCommonSpotPrice,isTradeDates} from '@/views/calc/otcOtion/instrument/common/common'
import {formartFormP4, formartTableP2, formartFormP2, unFormartNumber, numberPrecision} from '@/utils/numberUtil'
import {validateDates} from "./common/validate";
import {computeType} from "./common/data";
import {linkPercentage,linkPrice}  from '@/views/calc/otcOtion/instrument/common/formula'

const getColor = () => {
  return form.data.payDirection == '1' ? '#E53C3C' : '#22BB98'
}
 const {proxy} = getCurrentInstance()
const productType = 'Vanilla'
const cpoyWait = ref(false)
const labelWidth = ref('111px')
const showVolRatesResult = ref(false)
const calcInvertVisible = ref(false)
const Dialog = reactive({
  showMoneynessOption: true,
  type: '',
  data: {
    valueAmount: '',
    labelAmount: '',
    valuePercentage: '',
    labelPercentage: '',
    moneynessOption:''
  }
})
const form = reactive({
  data: {
    fixedRate: '',
    readOnly: false,
    productType: 'Vanilla',
    payDirection: '1',
    instrumentId: null,
    optionType: 'Call',
    effectiveDate: proxy.$moment(new Date()).format('YYYY-MM-DD'),
    terminationDate: '',
    terminationPaymentDate: '',
    term: '30',
    paymentDaysOffset: '0',
    priceOnWait: '0',
    spotPrice: '100',
    strikePercentage: '100',
    strike: 0,
    notional: '100000',
    optionEntitlement: '',
    moneynessOption: '1',
    daycounter: 'Actual/365',
    participationRate: 100,
    calendar: 'CHINA_EX',
    daycounterTerm: '365',
    exerciseType: 'European',
    isIncludeEndDate: '',
    endDate: '',
    isIncludeStartDate: '',
    startDate: '',
  },
  result: {},
  initFlag: ''
})
const rules = {
  payDirection: [{required: true, message: '请选择交易方向', trigger: 'change'}],
  instrumentId: [{required: true, message: ' ', trigger: 'change'}],
  optionType: [{required: true, message: '请选择涨跌类型', trigger: 'change'}],
  effectiveDate: [{required: true, message: ' ', trigger: 'change'}],
  terminationDate: [{required: true, message: ' ', trigger: 'change'}],
  term: [{required: true, message: ' ', trigger: 'change'}],
  paymentDaysOffset: [{required: true, message: ' ', trigger: 'change'}],
  notional: [{required: true, message: ' ', trigger: 'change'}, {
    validator: (rule, value, callback) => {
      return Number(value) > 0
    }, message: ' ', trigger: 'change'
  }],
  daycounter: [{required: true, message: ' ', trigger: 'change'}],
  daycounterTerm: [{required: true, message: ' ', trigger: 'change'}],
  spotPrice: [{required: true, message: ' ', trigger: 'change'}, {
    validator: (rule, value, callback) => {
      if (form.data.priceOnWait == '1') {
        return true
      }
      return Number(value) > 0
    }, message: ' ', trigger: 'change'
  }],
  optionEntitlement: [{required: true, message: ' ', trigger: 'change'}, {
    validator: (rule, value, callback) => {
      if (form.data.priceOnWait == '1') {
        return true
      }
      return Number(value) > 0
    }, message: ' ', trigger: 'change'
  }],
  strike: [{required: true, message: ' ', trigger: 'blur'}, {
    validator: (rule, value, callback) => {
      if (form.data.priceOnWait == '1'&&Number(form.data.strikePercentage)>0) {
        return true
      }
      return Number(value) > 0
    }, message: ' ', trigger: 'change'
  }],
  strikePercentage: [{required: true, message: ' ', trigger: 'change'}, {
    validator: (rule, value, callback) => {
      if (form.data.priceOnWait == '1'&&Number(form.data.strike)>0) {
        return true
      }
      return Number(value) > 0
    }, message: ' ', trigger: 'change'
  }],
  participationRate: [{required: true, message: ' ', trigger: 'change'}],
  paymentAmountPecentage: [{required: true, message: ' ', trigger: 'change'}],
  paymentAmount: [{required: true, message: ' ', trigger: 'change'}],
}

watch(() => props.result, async (nv, ov) => {
   nextTick(()=>{
     let other = {
       'type': '香草',
       '标的': computed(() => {
         if (proxy.$refs.underlyerIdRef&&proxy.$refs.underlyerIdRef.underlyerIdsList[0]) {
           return (proxy.$refs.underlyerIdRef.underlyerIdsList[0].productName+'').trim().split(' ').join(',')
         }
       }),
       "交易单位":"yuan",
       '交易日期': props.valueDate,
       '行权方式': form.data.exerciseType == 'European' ? '欧式行权' : '美式行权',
       '合约类型': form.data.optionType == 'Call' ? 'C' : 'P',
       '合约交易方向': form.data.payDirection == '1' ? '客户卖出' :  '客户买入',
       '到期日': form.data.terminationDate,
       '执行价': formartFormP2(form.data.strike, 2),
       '数量': formartFormP2(form.data.optionEntitlement),
       '名义金额': formartFormP2(form.data.notional),
       // '开仓标的价': formartFormP2(form.data.spotPrice),
       '开仓标的价': formartFormP2(nv.spotPrice),
       '期权单价': computed(() => {
         if (nv) {
           return formartFormP2(nv.npv / form.data.optionEntitlement)
         }
       }),
       '百分比估值': computed(() => {
         if (nv) {
           return formartFormP2(100 * nv.npv / form.data.notional)
         }
       }),
     }
     form.result = Object.assign(other, nv)
   })
},{
  immediate: true,
  deep: true
})

watch(() => form.data.priceOnWait, (nv, ov) => {
  if (form.data.priceOnWait == '1') {
    form.data.spotPrice = 0
  } else {
    setSpotPrice()
  }
})
/*
* 修改状态  false:当前没有操作  true:当前在被其他方法操作
* */
const lock = reactive({
  paymentDaysOffset: false,
  terminationPaymentDate: false,
})
watch(() => form.data.paymentDaysOffset, (nv, ov) => {
  if (nv === '') return
  if (lock.terminationPaymentDate) return
  lock.terminationPaymentDate = true
  onpaymentDaysOffsetChange()
})
const onpaymentDaysOffsetChange = debounce(function () {
  getTerminationPaymentDate({
    'calDay': form.data.terminationDate,
    'offset': form.data.paymentDaysOffset
  }).then(response => {
    lock.terminationPaymentDate = false
    if (response.errorCode != 0) {
    } else {
      form.data.terminationPaymentDate = response.result.CAL_DAY
    }
  })
}, 1000)
watch(() => form.data.terminationPaymentDate, (nv, ov) => {
  if (nv == ov || nv === '') return
  if (lock.paymentDaysOffset) return
  lock.paymentDaysOffset = true
  onterminationPaymentDate()
})
const onterminationPaymentDate = debounce(function (nv, ov) {
  getOffset({
    'day': form.data.terminationPaymentDate,
    'calDay': form.data.terminationDate
  }).then(response => {
    if (response.errorCode != 0) {

    } else {
      if (response.result == null) {
        onpaymentDaysOffsetChange()
        return
      }
      form.data.paymentDaysOffset = response.result.i
      lock.paymentDaysOffset = false
    }
  })
}, 1000)
onUnmounted(() => {
  // 移除组件时，取消定时器
  onpaymentDaysOffsetChange.cancel()
  onterminationPaymentDate.cancel()
})
const onBlurTerminationDate= (nv, ov) => {
  let a = proxy.$moment(form.data.terminationDate)
  let b = proxy.$moment(form.data.terminationPaymentDate)
  form.data.paymentDaysOffset = b.diff(a, 'days')
}
watch(() => [form.data.effectiveDate, form.data.terminationDate], ([nv, n2v], [ov, o2v]) => {
  if (!proxy.lsh.isEmpty(nv) && !proxy.lsh.isEmpty(n2v)) {
    let a = proxy.$moment(n2v)
    let b = proxy.$moment(nv)
    form.data.term = Number(a.diff(b, 'days'))
   proxy.$refs.PricingParamRef?proxy.$refs.PricingParamRef.calcRateByCode():''
  }
})

const onBlurEffectiveDate = () => {
  form.initFlag = false
  setSpotPrice()
}

watch(() => [form.data.term], ([newValue], [oldValue]) => {
  if (isNotVoid(String(form.data.effectiveDate)) && isNotVoid(String(newValue))) {
    let a = proxy.$moment(form.data.effectiveDate)
    form.data.terminationDate = a.add(newValue, 'days').format('YYYY-MM-DD')
    onpaymentDaysOffsetChange()
  }
})
// ------
watch(() => [form.data.notional, form.data.spotPrice], ([nv, n2v], [ov, o2v]) => {
  if (!proxy.lsh.isEmpty(nv) && !proxy.lsh.isEmpty(n2v)) {

    form.data.optionEntitlement = String(Number(nv) / Number(n2v))
  }
})

// ------
watch(() => [form.data.notional], ([newValue], [oldValue]) => {
  if (optionEntitlementLinkValid(newValue, form.data.spotPrice, form.data.optionEntitlement)) {
    return
  }
  if (isNotVoid(String(newValue))) {
    if (isNotVoid(String(form.data.spotPrice))) {
      form.data.optionEntitlement = proxy.lsh.divide(newValue, form.data.spotPrice).toFixed(4)
      return
    }
    if (isNotVoid(String(form.data.optionEntitlement))) {
      form.data.spotPrice = proxy.lsh.divide(newValue, form.data.optionEntitlement).toFixed(4)
      return
    }
  }
})
// ------
watch(() => [form.data.spotPrice], ([newValue], [oldValue]) => {
  if (optionEntitlementLinkValid(form.data.notional, newValue, form.data.optionEntitlement)) {
    return
  }
  if (isNotVoid(String(newValue))) {
    if (isNotVoid(String(form.data.notional))) {
      form.data.optionEntitlement = proxy.lsh.divide(form.data.notional, newValue)
      return
    }
    if (isNotVoid(String(form.data.optionEntitlement))) {
      form.data.notional = proxy.lsh.multiply(form.data.optionEntitlement, newValue).toFixed(4)
      return
    }
  }
})
// ------
const optionEntitlementChange = (newValue) => {
  if (form.data.priceOnWait == '1') return
  if (optionEntitlementLinkValid(form.data.notional, form.data.spotPrice, newValue)) {
    return
  }
  if (isNotVoid(String(newValue))) {
    if (isNotVoid(String(form.data.spotPrice))) {
      form.data.notional = proxy.lsh.multiply(newValue, form.data.spotPrice).toFixed(0)
      return
    }
    if (isNotVoid(String(form.data.notional))) {
      form.data.spotPrice = proxy.lsh.divide(form.data.notional, newValue).toFixed(4)
      return
    }
  }
}


watch(() => [form.data.spotPrice], ([newValue], [oldValue]) => {
  linkPrice(form,form.data.strike,form.data.spotPrice,'data.strikePercentage')
})
function optionEntitlementLinkValid(notional, spotPrice, optionEntitlement) {
  if (Boolean(Number(notional)) && Boolean((Number(spotPrice))) && Boolean(Number(optionEntitlement))) {
    if (proxy.lsh.isEqual(optionEntitlement, proxy.lsh.divide(notional, spotPrice).toFixed(4))) {
      return true
    } else {
      return false
    }
  }
}

watch(() => [props.cfgId,form.data.instrumentId], ([newId, oldId]) => {
  getPricingCfg()
  setTimeout(() => {
    proxy.$refs.PricingParamRef?proxy.$refs.PricingParamRef.calcRateByCode():''
  }, 1000);
})

const onBlurInstrumentId = () => {
  setSpotPrice()
  getPricingCfg()
  setTimeout(() => {
    proxy.$refs.PricingParamRef?proxy.$refs.PricingParamRef.calcRateByCode():''
  }, 1000);
}

watch(()=>form.data,()=>{
  proxy.$attrs.cacheFormData()
},{immediate:true})
watch(() => props.valueDate, (newValue, oldValue) => {
  if (newValue != oldValue) {
    setSpotPrice()
    //触发修改定价参数的价格
    proxy.$refs.PricingParamRef.setSpotPrice({
      valueDate:props.valueDate,
      instrumentId:form.data.instrumentId
    })
   proxy.$refs.PricingParamRef?proxy.$refs.PricingParamRef.calcRateByCode():''
  }
})

watch(() => form.data.exerciseType, (nv, ov) => {
  if (form.data.exerciseType == 'American') {
    form.data.startDate = form.data.effectiveDate
    form.data.endDate = form.data.terminationDate
  }
}, {
  immediate: true
})
watch(() => [form.data.effectiveDate, form.data.terminationDate], () => {
  if (form.data.exerciseType == 'American') {
    form.data.startDate = form.data.effectiveDate
    form.data.endDate = form.data.terminationDate
  }
})
const props = defineProps({
  calcMarketNpvResult: {
    type: Object,
    default: {}
  },
  /*是否为重放*/
  isReCalc: {
    type: Boolean,
    default: false
  },
  calcSuccess:{
    type: String,
    default: ''
  },
  errorMsg:{
    type: String,
    default: ''
  },
  useType: {
    type: String,
    default: 'calc'
  },
  index: {
    type: String,
    default: ''
  },
  del: {
    type: Function,
    default: null
  },
  copy: {
    type: Function,
    default: null
  },
  calc: {
    type: Function,
    default: null
  },
  marketNPV: {
    type: Function,
    default: null
  },
  save2Trade: {type: Function, default: null},
  save2CalcLog: {type: Function, default: null},
  getDefaultCfg: {
    type: Function,
    default: null
  },
  calcPricingParam: {
    type: Object,
    default: {}
  },
  result: {
    type: Object,
    default: {}
  },
  setformData: {
    type: Function,
    default: null
  },
  formData: {
    type: Object,
    default: null
  },
  cfgId: {type: String, default: ''},
  valueDate: {type: String, default: ''}
})
const getResult = () => {
  var data = []
  for (var item in props.result) {
    if (['npv', 'delta', 'gamma', 'vega', 'theta', 'rho', 'spotPrice', 'dscRate'].includes(item)) {
      data.push({
        key: item,
        val: proxy.lsh.ceil(props.result[item], 4)
      })
    }
  }
  return data
}

//定价参数
const getPricingCfg = async () => {
  let query = {
    'calcPricingParam': {
      'cfgId': props.cfgId
    },
    'instrument': {
      'productType': 'Vanilla',
      'termsheet': {
        'underlyerIds': [form.data.instrumentId],
        'customLegs': [{
          'legId': 'leg01',
          'productType': 'Vanilla'
        }
        ],
        'legs': [{
          'legId': 'leg01',
          'payDirection': form.data.payDirection
        }
        ]
      }
    }
  }
  //设置定价参数中的定盘价
  proxy.$refs.PricingParamRef.setSpotPrice({
    valueDate:props.valueDate,
    instrumentId:form.data.instrumentId
  })
  if (props.getDefaultCfg != null) {
    props.getDefaultCfg(query, props.index)
  }
}
const cancel = () => {
  props.del(props.index)
}
const copy = () => {
  props.copy(props.index)
  cpoyWait.value = true;
  setTimeout(() => {
    cpoyWait.value = false;
  }, 1000);
}
const calc = (flag) => {
  /*flag 标识 为All时单次计算不会提示成功或失败*/
  getInstrumentJson().then((res) => {
    if (Boolean(res)) {
      let otcOption = res.otcOption
      otcOption.calcInstrumentForm = res.calcInstrumentForm
      otcOption.calcPricingForm = res.calcPricingForm
      if (otcOption != '') {
        props.calc(otcOption, props.index, flag)
      }
      showVolRatesResult.value = false
    }
  })
}
const getInstrumentJson = async () => {
  return new Promise((resolve) => {
    proxy.$refs['formRef'].validate(valid => {
      if (valid) {
        validateDates(form)
        resolve(convertJson())
      } else {
        resolve('')
      }
    })
  })
}
const save2Trade = () => {
  getInstrumentJson().then((res) => {
    if (Boolean(res)) {
      props.save2Trade(res, props.index)
    }
  })

}
const marketNPV = () => {
  getInstrumentJson().then((res) => {
    if (Boolean(res)) {
      showVolRatesResult.value = true
      let {otcOption} = res
      // proxy.$refs.resultCompRef.getNewNpv()
      res['instrument'] = otcOption.instrument
      res.otcOption.calcPricingParam['marketNPV'] = proxy.$refs.resultCompRef.getNewNpv()
      res['calcPricingParam'] = res.otcOption.calcPricingParam
      props.marketNPV(res, props.index)
    }
  })

}
const save2CalcLog = () => {
  getInstrumentJson().then((res) => {
    if (Boolean(res)) props.save2CalcLog(res, props.index)
  })

}
const getCalcPriceParam = (calcType) => {
  let calcPriceParam = proxy.$refs.PricingParamRef.getCalcPricingParam(calcType)
  return calcPriceParam
}

const getFormData = () => {
  return form
}
const setSpotPrice = () => {
  setCommonSpotPrice(proxy,form,props)
}
const convertJson = (calcType) => {
  let calcPriceParam = getCalcPriceParam(calcType)
  let otcOption = {
    instrument: {
      'termsheet': {
        'notional': form.data.notional,
        'notionalCurrency': 'CNY',
        'settlementType': 'C',
        'settlementCurrency': 'CNY',
        'effectiveDate': form.data.effectiveDate,
        'effectiveDateConv': 'Following',
        'terminationDate': form.data.terminationDate,
        'terminationDateConv': 'Following',
        'terminationDateCalendar': form.data.calendar,
        'underlyerIds': [
          form.data.instrumentId
        ],
        'calendars': [
          form.data.calendar
        ],
        'legs': [
          {
            'legId': 'leg01',
            'payDirection': form.data.payDirection
          }
        ],
        'customLegs': [
          {
            'payDirection': form.data.payDirection,
            periodOfAccrualInterestAdjust: '0',
            'participationRate': String(form.data.participationRate / 100),
            'productType': 'Vanilla',
            'optionType': form.data.optionType,
            'strike': form.data.strike,
            'strikePercentage': form.data.strikePercentage / 100,
            'exercise': {
              'type': form.data.exerciseType,
              'dates': form.data.exerciseType == 'American' ? [form.data.startDate, form.data.endDate] : [form.data.terminationDate],
              'conv': 'Following',
              'calendar': form.data.calendar
            },
            'paymentDateCalendar': form.data.calendar,
            'underlyers': [
              {
                'instrumentId': form.data.instrumentId,
                'quoteType': '',
                'spotPrice': form.data.spotPrice,
                'basketWeight': '1',
                'fixingDate': '',
                'fixingDateConv': 'Preceding',
                'fixingDateCalendar': form.data.calendar
              }
            ],
            'numberOfOptions': '1',
            'optionEntitlement': form.data.optionEntitlement,
            'moneynessOption': form.data.moneynessOption,
            'daycounter': form.data.moneynessOption == '1' ? form.data.daycounter : '',
            'fixingRounding': '-1',
            'settlementDateConv': 'Following',
            'settlementDateCalendar': form.data.calendar,
            'settlementDateOffset': form.data.paymentDaysOffset + 'D',
            'legId': 'leg01'
          }
        ],
        'term': form.data.term,

      },
      'productType': 'Vanilla'
    },
    calcPricingParam: {
      valueDate: props.valueDate,
      cfgId: props.cfgId,
      calcPPCode: calcPriceParam.calcPPCode,
      underlyingPricingParams: [
        {
          underlyingID: form.data.instrumentId,
          dividend: calcPriceParam.dividend,
          volSurface: calcPriceParam.volSurface,
          funding: calcPriceParam.discount,
          spotPrice: calcPriceParam.spotPrice,
          spotQuoteType: calcPriceParam.spotQuoteType
        }
      ],
      discount: calcPriceParam.discount,
      'customPricingParam': {}
    },
    underlyingMarkets: [
      {
        'underlyingID': form.data.instrumentId,
        'fixingPrices': [],
        'observerPrices': []
      }
    ]
  }
  let calcInstrumentForm = toRaw(form.data)
  let result = props.result
  let json = {
    otcOption: otcOption,
    calcInstrumentForm: calcInstrumentForm,
    calcPricingForm: calcPriceParam,
    calcResultForm: result
  }
  return json
}
//反算逻辑
const calcInvert = () => {
  let json = convertJson("invert");
  let {newNpv, yearnpvPercentage, npvPercentage, showSwitch} = proxy.$refs.resultCompRef.getData();
  if (showSwitch) {
    if (isVoid(yearnpvPercentage)) {
      proxy.$modal.msgWarning("请填入npv%");
      return;
    }
  } else {
    if (isVoid(npvPercentage)) {
      proxy.$modal.msgWarning("请填入npv%");
      return;
    }
  }
  json.otcOption.calcPricingParam["marketNPV"] = form.data.notional * npvPercentage / 100;
  if(form.data.strikePercentage != '0.00'){
    proxy.$modal.msgWarning("请空出反算要素");
    return;
  }


  //行权价/比例
  if (0==form.data.strikePercentage) {
    json.otcOption["contractRoots"] = {
      "contractRoot": [
        {
          "computeType": computeType.STRIKE,
          "index": 0
        }
      ]
    }
    calcContractParamProxy(json.otcOption).then((result) => {
      let amounts = result.amounts.double;
      let ratios = result.ratios.double;
      if (amounts.length > 1) {
        //todo 多个返回值时舍去值的逻辑

      }
      let amountsTarget = amounts[0];
      let ratiosTarget = ratios[0];

      calcInvertVisible.value = true
      Dialog.type = "strikePercentage"
      Dialog.showMoneynessOption = false
      form.data.strike = amountsTarget
      form.data.strikePercentage = ratiosTarget * 100
      Dialog.data.valueAmount = amountsTarget;
      Dialog.data.valuePercentage = form.data.strikePercentage;
      Dialog.data.labelAmount = "行权价"
      Dialog.data.labelPercentage = "行权价比例"
      proxy.$refs.PricingParamRef?proxy.$refs.PricingParamRef.calcRateByCode():''

      proxy.$modal.msgSuccess("计算成功！");
    })

  }
}

/*将proxy 暴露出去 给报价导出使用*/
defineExpose({
  calc, getPricingCfg, getCalcPriceParam, getFormData, getInstrumentJson,proxy
})
onMounted(() => {
  /*获取默认定价配置*/
  // getPricingCfg()
  /*获取预填表单*/

  // if (props.formData.data != null) {
  //   let a = Object.assign(form.data,props.formData)
  //   form.data = a;
  // }
  form.initFlag = props.isReCalc

  if (props.formData != null) {
    form.initFlag = isNotVoid(props.calcPricingParam)
    let data = props.formData.data || props.formData
    form.data = Object.assign(form.data, data)
  }
  // 这里获取DOM的value是旧值
  nextTick(()=>{
    form.initFlag = false
  })
})
watch(() => proxy.$attrs.disabled, (nv) => {
  form.data.readOnly = nv
}, {
  immediate: true
})
watch(()=>form,()=>{

  proxy.$attrs.cacheFormData()
},{deep:true})
</script>
<style scoped>
.cardClass {
  /*border-color: v-bind(color.value);*/
  width: 350px;
}
</style>

